|
|
|
|
|
|
|
After the object instance is created, all you have to do to establish a connection is provide the connection string and call the Open method. You can set the connection string in two ways, the first being to assign it to the ConnectionString property: |
|
|
|
|
|
|
|
|
cn.ConnectionString = "DSN=BIBLIO"
cn.Open |
|
|
|
|
|
|
|
|
You can also pass the connection string as part of the call to the Open method: |
|
|
|
|
|
|
|
|
|
The connection string shown here is simple. For other data sources, your connection string may be longer and include additional information.  |
|
|
|
|
|
|
|
|
|
|
After you finish using a connection, call the Close method. As with most object variables, it is also a good idea to set them to Nothing to free up any used resources: |
|
|
|
|
|
|
|
|
cn.Close
Set cn = Nothing |
|
|
|
|
|
|
|
|
In ADO, you can accomplish the same goal in many different ways. Retrieving information is a perfect example. You can take your pick from the Recordset, Command, or Connection objects; they all have a method used to pull data into a recordset. The Connection object's Execute method allows you to run an SQL statement against a data source. If the SQL statement returns records, you can access them simply by assigning the return value of the Execute method to an ADO Recordset object. |
|
|
|
|
|
|
|
|
Test the Execute method with a simple example. Start a new Standard EXE project, and add a reference to ADO. Then add a list box control to the form, and name it lstAuthors. Finally, place the following lines of code in the form's Load event: |
|
|
|
|
|
|
|
|
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "DSN=BIBLIO"
Set rs = cn.Execute("Select * from Authors Where [Year Born] > 1943")
While Not rs.EOF
lstAuthors.AddItem "Year Born: " & rs.Fields("Year Born") & vbTab _
& "Name: " & rs.Fields("Author")
rs.MoveNext
Wend
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing |
|
|
|
|
|
|
|
|
Run the program, and you should see results similar to those pictured in Figure 24.16. |
|
|
|
|
|